package cn.xy.ymcc.mq.consumer;

import cn.xy.ymcc.domain.PayOrder;
import cn.xy.ymcc.dto.PayDto;
import cn.xy.ymcc.service.IPayOrderService;
import cn.xy.ymcc.util.AssertUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Date;

/**
 * 课程订单生成支付单的消费者
 */
@Slf4j
@Component
@RocketMQMessageListener(
        consumerGroup="course-order-pay-consumer",
        topic="course-order-topic",
        selectorExpression="course-order-tag"

)
public class CourserOrder2PayOrderConsumer implements RocketMQListener<MessageExt> {
    @Autowired
    private IPayOrderService payOrderService;

    @Override
    public void onMessage(MessageExt messageExt) {
        //获取生产者的消息体
        byte[] body = messageExt.getBody();
        //断言
        AssertUtil.isNotNull(body,"消息体为空");
        //转为string格式
        String jsonStr = new String(body, StandardCharsets.UTF_8);
        //转为paydto格式
        PayDto payDto = JSONObject.parseObject(jsonStr, PayDto.class);
        //根据订单号拿到对应支付单
        PayOrder payOrder = payOrderService.selectByOrderNo(payDto.getOrderNo());
        //判断是否存在
        if(payOrder != null){  //已经存在，说明已经被别人消费过了，直接签收消息。
            log.info("订单已经存在，不再消费消息，直接签收！！");
            return;
        }
        //不存在则说明是第一次来消费这个消息，需要保存支付单
        //但是支付单数据不完全，需要合并,并且设置固定值
        payOrder = new PayOrder();
        BeanUtils.copyProperties(payDto,payOrder);
        payOrder.setCreateTime(new Date());
        payOrder.setPayStatus(PayOrder.STATE_WAIT_PAY);
        payOrderService.insert(payOrder);







    }
}
